package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 14:14
 */
public class BipartitionDetection1 {

    private Graph G;
    private boolean[] visited;
    private int[] colors;
    private boolean isBipartite = true;

    public BipartitionDetection1(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];
        this.colors = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                if (!dfs(i, 1)) {
                    isBipartite = false;
                    break;
                }
            }
        }
    }

    private boolean dfs(int v, int color) {
        visited[v] = true;
        this.colors[v] = color;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                if (!dfs(w, 3 - color)) {
                    return false;
                }
            } else {
                if (this.colors[w] == color) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args) {
        String filename = BipartitionDetection1.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        BipartitionDetection1 biPartitionDetection = new BipartitionDetection1(g);
        System.out.println(biPartitionDetection.isBipartite());

        String filename2 = BipartitionDetection1.class.getClassLoader().getResource("g3.txt").getPath();
        Graph g2 = new Graph(filename2);
        BipartitionDetection1 biPartitionDetection2 = new BipartitionDetection1(g2);
        System.out.println(biPartitionDetection2.isBipartite());
    }
}
